from quart import Quart, request, jsonify
import traceback, asyncio

from imageNodes import imageFlowExecutor

app = Quart(__name__)

@app.post("/exec")
async def onExecReq():
    data = await request.get_json()

    try:
        nodes = imageFlowExecutor.load_from_json(data)

        await asyncio.to_thread(imageFlowExecutor.exec_BFS, nodes)

        result = imageFlowExecutor.get_result()

        return jsonify({"status":"success", "result":result})


    except Exception:
        app.logger.error("runtime error")
        traceback.print_exc()
        return jsonify({
            "status":"runtime error"
        })

app.run(port=5056, debug=True)


# is_executing = False
# @app.post("/exec")
# async def onExecReq():
#     data = await request.get_json()

#     try:
#         global is_executing
#         nodes = imageFlowExecutor.load_from_json(data)

#         is_executing = True
#         await asyncio.to_thread(imageFlowExecutor.exec_BFS, nodes)
#         is_executing = False

#         #获取运行结果
#         result = imageFlowExecutor.get_result()
#         return jsonify({"status":"success", "result":result})


#     except Exception:
#         is_executing = False
#         app.logger.error("runtime error")
#         traceback.print_exc()
#         return jsonify({
#             "status":"runtime error"
#         })

# # 定期清理图片缓存
# async def clean_cache():
#     while True:
#         if os.listdir('./cache') and not is_executing:
#             shutil.rmtree('cache')
#             os.mkdir('cache')
#             app.logger.info("@clean cache")

#         await asyncio.sleep(60, loop=loop)

  
# loop = asyncio.get_event_loop()
# loop.create_task(app.run_task(port=5056, debug=True))
# loop.create_task(clean_cache())

# loop.run_forever()